﻿using System;
using System.Diagnostics;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eksponent.CropUp.JavaScript;
using umbraco.cms.businesslogic.datatype;
using umbraco.interfaces;
using Content = umbraco.cms.businesslogic.Content;

[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.CropUp.js", "text/javascript")]
[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.CropUp.Editor.js", "text/javascript")]
[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.jquery.color.js", "text/javascript")]
[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.jquery.Jcrop.min.js", "text/javascript")]
[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.json2.js", "text/javascript")]
[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.CropUp.css", "text/css")]
[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.jquery.Jcrop.css", "text/css")]
[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.Jcrop.gif", "image/gif")]
[assembly: WebResource("Eksponent.CropUp.Umbraco.Resources.bias-handle.png", "image/png")]



namespace Eksponent.CropUp.Umbraco
{
    public class Cropper : Control, IDataEditor
    {
        private readonly CropUpDataType _data;
        private Panel _container;
        private HtmlInputControl _dataField;

        public Cropper(CropUpDataType data)
        {
            _data = data;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Controls.Add(new LiteralControl(string.Format(
@"<style type='text/css'>
    @import url('{0}');@import url('{1}');
    .jcrop-vline, .jcrop-hline {{ background-image: url('{2}'); }}
    .crop-up-editor .bias-handle {{background-image: url('{3}'); }}
</style>",
                Page.ClientScript.GetWebResourceUrl(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.CropUp.css"),
                Page.ClientScript.GetWebResourceUrl(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.jquery.Jcrop.css"),
                Page.ClientScript.GetWebResourceUrl(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.Jcrop.gif"),
                Page.ClientScript.GetWebResourceUrl(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.bias-handle.png"))));

            Page.ClientScript.RegisterClientScriptResource(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.jquery.color.js");
            Page.ClientScript.RegisterClientScriptResource(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.jquery.Jcrop.min.js");
            Page.ClientScript.RegisterClientScriptResource(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.json2.js");
            Page.ClientScript.RegisterClientScriptResource(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.CropUp.js");
            Page.ClientScript.RegisterClientScriptResource(typeof(Cropper), "Eksponent.CropUp.Umbraco.Resources.CropUp.Editor.js");

            _container = new Panel { ID = "Container" };
            _dataField = new HtmlInputHidden();
            _container.Controls.Add(_dataField);


            Controls.Add(_container);

        }

        private bool _imageChanged = false;

        private ClientDataConverter _clientData;
        protected ClientDataConverter ClientData
        {
            get
            {
                var p = new Content(((DefaultData)_data.Data).NodeId).getProperty(((CropperPrevalueEditor)_data.PrevalueEditor).ImageProperty);
                if (p != null && p.Value != null && !string.IsNullOrEmpty((string)p.Value))
                {
                    var path = "" + p.Value;
                    if (_clientData != null && path != _clientData.ImagePath)
                    {
                        _imageChanged = true;
                    }

                    if (File.Exists(HostingEnvironment.MapPath(path)))
                    {
                        return _clientData = new ClientDataConverter(path);
                    }
                }

                return _clientData = new ClientDataConverter(null);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (ClientData.ImagePath != null)
            {
                _container.CssClass = "crop-up-editor";

                var data = ClientData.GetCropperData();
                var json = new JavaScriptSerializer();
                if (!Page.IsPostBack || string.IsNullOrEmpty(_dataField.Value) || _imageChanged)
                {
                    _dataField.Value = json.Serialize(data.data);
                }

                data.src = CropUp.GetUrl(ClientData.ImagePath, new ImageSizeArguments { Width = 400, Height = 350, CropMode = CropUpMode.Max });
                Page.ClientScript.RegisterClientScriptBlock(typeof(Cropper), "Load_" + _container.ClientID,
                    string.Format("jQuery(function(){{jQuery('#{0}').cropUpEditor({1});}});",
                    _container.ClientID,
                    json.Serialize(data)
                 ), true);

            }
            else
            {
                _container.Controls.Add(new LiteralControl("<div class='error'>No image is specified / image cannot be found</div>"));
            }
        }


        public void Save()
        {
            _data.Data.Value = _dataField.Value;
            ClientData.Save(_dataField.Value);

        }

        public bool ShowLabel
        {
            get { return true; }
        }

        public bool TreatAsRichTextEditor
        {
            get { return false; }
        }

        public Control Editor
        {
            get { return this; }
        }
    }
}
